package com.itelite.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.io.File;

@Configuration
public class CorsConfiguration extends WebMvcConfigurationSupport {
    /*
     * 这里主要为了解决跨域问题,所以重写addCorsMappings方法
     */
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        // 设置允许跨域的路由
        registry.addMapping("/**")
                // 设置允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 是否允许证书（cookies）
                .allowCredentials(true)
                // 设置允许的方法
                .allowedMethods("*")
                // 跨域允许时间
                .maxAge(3600);
    }
    /**
     * 跨域配置后swagger2可能不能访问，需要增加如下配置
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("swagger-ui.html")
                .addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");

        registry.addResourceHandler("/record/**")
                .addResourceLocations("file:"+WebAppConfig.ROOT+File.separator+WebAppConfig.ROOT_DIR_RECORD+File.separator);
        registry.addResourceHandler("/prize/**")
                .addResourceLocations("file:"+WebAppConfig.ROOT+File.separator+WebAppConfig.ROOT_DIR_PRIZE+File.separator);
        registry.addResourceHandler("/cover/**")
                .addResourceLocations("file:"+WebAppConfig.ROOT+File.separator+WebAppConfig.ROOT_DIR_COVER+File.separator);
        registry.addResourceHandler("/config/**")
                .addResourceLocations("file:"+WebAppConfig.ROOT+File.separator+WebAppConfig.ROOT_DIR_CONFIG+File.separator);
    }
}

